<template>
	<section class="userlist-con">
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters" @submit.native.prevent>
				<el-form-item>
					<el-input v-model="filters.name" placeholder="姓名" clearable @clear="getUsers"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="handleCurrentChange(1);getUsers">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
        <el-form-item>
					<el-button type="primary" @click="output">导出Excel</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="users" highlight-current-row @selection-change="selsChange" style="width: 100%;" id="users">
			<el-table-column type="selection" width="40">
			</el-table-column>
			<el-table-column type="index" width="30">
			</el-table-column>
      <el-table-column prop="image" label="头像" width="60">
        <template slot-scope="scope">
          <img :src="scope.row.image" width="40" height="40">
        </template>
			</el-table-column>
			<el-table-column prop="name" label="姓名" width="60">
			</el-table-column>
      <el-table-column prop="email" label="邮箱" width="160">
			</el-table-column>
      <el-table-column prop="phone" label="电话" width="100">
			</el-table-column>
      <el-table-column prop="balance" label="余额" width="60">
			</el-table-column>
			<el-table-column prop="sex" label="性别" width="60" :formatter="formatSex">
			</el-table-column>
			<el-table-column prop="age" label="年龄" width="50">
			</el-table-column>
			<el-table-column prop="birth" label="生日" width="100">
			</el-table-column>
			<el-table-column prop="addr" label="地址" min-width="120">
			</el-table-column>
      <el-table-column prop="role" label="角色" width="60" :formatter="formatRole">
			</el-table-column>
      <el-table-column prop="role" label="状态" width="60" :formatter="formatStatus">
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template slot-scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar clearfix">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0" class="plBtn">批量删除</el-button>
			<!-- <el-pagination layout="total,sizes,prev, pager, next" @current-change="handleCurrentChange" :page-size="20" :total="total" style="float:right;">
			</el-pagination> -->
      <el-pagination @size-change="handleCountChange" @current-change="handleCurrentChange" :current-page="page" :page-sizes="[5,10,20]" :page-size="count" layout="total, sizes, prev, pager, next, jumper" :total="total" style="float:right;">
      </el-pagination>
		</el-col>

		<!--添加用户界面-->
		<el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="60%">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="姓名" prop="name">
					<el-input v-model="editForm.name" auto-complete="off"  :disabled="dialogStatus==='update'?true:false" clearable></el-input>
				</el-form-item>
        <!-- <el-form-item label="头像" prop="image">
					<el-input v-model="editForm.image" auto-complete="off"></el-input>
				</el-form-item> -->
        <el-form-item label="电话" prop="phone">
					<el-input v-model="editForm.phone" auto-complete="off"  :disabled="dialogStatus==='update'?true:false" clearable></el-input>
				</el-form-item>
        <el-form-item label="邮箱" prop="email">
					<el-input v-model="editForm.email" auto-complete="off"  :disabled="dialogStatus==='update'?true:false" clearable></el-input>
				</el-form-item>
        <!-- <el-form-item label="余额" prop="balance">
					<el-input v-model="editForm.balance" auto-complete="off"></el-input>
				</el-form-item> -->
				<el-form-item label="性别">
					<el-radio-group v-model="editForm.sex">
						<el-radio class="radio" :label=1 :disabled="dialogStatus==='update'?true:false">男</el-radio>
						<el-radio class="radio" :label=0  :disabled="dialogStatus==='update'?true:false">女</el-radio>
					</el-radio-group>
				</el-form-item>
        <!-- 管理员修改只能该角色和激活状态 -->
        <el-form-item label="角色">
					<el-radio-group v-model="editForm.role">
						<el-radio class="radio" :label="'admin'">管理员</el-radio>
						<el-radio class="radio" :label="'normal'">普通用户</el-radio>
					</el-radio-group>
				</el-form-item>
        <!-- 默认创建用户时就是激活状态，不能修改 -->
        <el-form-item label="账户状态" v-if="dialogStatus=='update'">
					<el-radio-group v-model="editForm.status">
						<el-radio class="radio" :label=1 :disabled="dialogStatus==='create'?true:false">激活</el-radio>
						<el-radio class="radio" :label=0 :disabled="dialogStatus==='create'?true:false">冻结</el-radio>
					</el-radio-group>
				</el-form-item>
				<!-- <el-form-item label="年龄">
					<el-input-number v-model="editForm.age" :min="0" :max="200"></el-input-number>
				</el-form-item>
				<el-form-item label="生日">
					<el-date-picker type="date" placeholder="选择日期" v-model="editForm.birth"></el-date-picker>
				</el-form-item>
				<el-form-item label="地址">
					<el-input type="textarea" v-model="editForm.addr"></el-input>
				</el-form-item> -->
			</el-form>
			<div slot="footer" class="dialog-footer">
			 <el-button @click.native="dialogFormVisible=false">取消</el-button>
			  <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">添加</el-button>
        <el-button v-else type="primary" @click="updateData">修改</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
import FileSaver from "file-saver"
import XLSX from "xlsx"
import util from '../../../utils/table.js'
import {
  getUserListPage,
  removeUser,
  batchRemoveUser,
  editUser,
  addUser
} from '../../../api/userTable'
export default {
  data() {
    // 验证邮箱
    let validateEamil = (rule, value, callback) => {
      // 调用vuex中异步函数validateEmail，将参数传进去
      this.$store.dispatch('validateEmail',{rule, value, callback})
    };
    // 验证手机号
    let validatePhone = (rule, value, callback) => {
      // 调用vuex中异步函数validateEmail，将参数传进去
      this.$store.dispatch('validatePhone',{rule, value, callback})
    };
    return {
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogFormVisible: false,
      filters: {
        name: ''
      },
      users: [],
      total: 0,
      page: 1,
      count:5,
      sels: [], // 列表选中列
      // 添加用户，管理员应该只需要填写必要信息，其它信息由用户自己完善
      // 这里添加和修改共用的一个对话框，只允许管理员修改用户权限和用户状态，通过三元表达式控制
      editForm: {
        id: '0',
        name: '',
        phone:'',
        email:'',
        role:'normal',
        sex: 0,
        status:1
      },
      editFormRules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入电话', trigger: 'blur' }],
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
        // phone: [{required: true, validator: validatePhone, trigger: "blur" }],
        // email: [{ required: true,validator: validateEamil, trigger: "blur" }]
      },
      addFormVisible: false, // 新增界面是否显示
    }
  },
  methods: {
    // 性别显示转换
    formatSex: function(row, column) {
      return row.sex === 1 ? '男' : row.sex === 0 ? '女' : '未知'
    },
    // 用户权限显示转换
    formatRole: function(row, column) {
      // 如果没有填，默认普通用户
      return row.role === 'admin' ? '管理员' : row.role === 'normal' ? '普通用户' : '管理员'
    },
    formatStatus: function(row, column) {
      return row.status === 1 ? '激活' : row.status === 0 ? '冻结' : '激活'
    },
    // 监听pagesize改变的事件
    handleCountChange(newSize) {
      this.count = newSize
      this.getUsers()
    },
    handleCurrentChange(val) {
      this.page = val
      this.getUsers()
    },
    // 获取用户列表
    getUsers() {
      const para = {
        page: this.page,
        name: this.filters.name,
        limit:this.count
      }
      getUserListPage(para).then(res => {
        console.log(res)
        this.total = res.data.data.total
        this.users = res.data.data.users
      }).catch((err) => {
        console.log(err)
      }); 
      /* this.$http.get('/user/listpage',{para}).then(res => {
        console.log(res)
        this.total = res.data.data.total
        this.users = res.data.data.users
      }).catch((err) => {
        console.log(err)
      }); */
    },
    // 删除
    handleDel(index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      })
        .then(() => {
          const para = { id: row.id }
          // this.$http.get('/user/remove',para).then(res => {
          removeUser(para).then(res => {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getUsers()
          })
        })
        .catch(() => {})
    },
    // 显示编辑界面
    handleEdit(index, row) {
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.editForm = Object.assign({}, row)
    },
    // 显示新增界面
    handleAdd() {
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      // 新增页不能渲染数据
      this.editForm = {
        id: '0',
        name: '',
        phone:'',
        email:'',
        role:'normal',
        sex: 0
      }
    },
    // 编辑
    updateData() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {})
            .then(() => {
              const para = Object.assign({}, this.editForm)
              para.birth =
                !para.birth || para.birth === ''
                  ? ''
                  : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd')
              // this.$http.get('/user/edit',para).then(res => {
              editUser(para).then(res => {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                })
                this.$refs['editForm'].resetFields()
                this.dialogFormVisible = false
                this.getUsers()
              })
            })
            .catch(e => {
              // 打印一下错误
              console.log(e)
            })
        }
      })
    },
    // 新增
    createData: function() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {})
            .then(() => {
              this.editForm.id = (parseInt(Math.random() * 100)).toString() // mock a id
              const para = Object.assign({}, this.editForm)
              console.log(para)
              // 格式化生日
              para.birth =
                !para.birth || para.birth === ''
                  ? ''
                  : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd')
              // this.$http.get('/user/add',para).then(res => {
              addUser(para).then(res => {
                console.log(res);
                if(res.data.code===1){
                  // this.$message.error(res.data.message);
                  this.$message({
                    message: res.data.data.message,
                    type: 'error'
                  })
                }else{
                  // this.$message.success(res.data.message);
                  this.$message({
                    message: res.data.data.message,
                    type: 'success'
                  })
                  this.$refs['editForm'].resetFields()
                  this.dialogFormVisible = false
                  this.getUsers() 
                }
              })
            })
            .catch(e => {
              // 打印一下错误
              console.log(e)
            })
        }
      })
    },
    // 全选单选多选
    selsChange(sels) {
      this.sels = sels
    },
    // 批量删除
    batchRemove() {
      var ids = this.sels.map(item => item.id).toString()
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          const para = { ids: ids }
          // this.$http.get('/user/batchremov',para).then(res => {
          batchRemoveUser(para).then(res => {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getUsers()
          })
        })
        .catch(() => {})
    },
    output() {
      /* generate workbook object from table */
      var wb = XLSX.utils.table_to_book(document.querySelector("#users"));//mytable为表格的id名
      /* get binary string as output */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          "sheet.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    }
  },
  created() {
    this.getUsers()
  }
}
</script>

<style scoped>
.userlist-con {
  margin-right:40px;
}
.toolbar {
  margin-top:20px;
}
.userlist-con{
  margin:10px 0 20px 10px;
}
.el-table th {
  text-align: center;
}
</style>